package com.jp.knowledge.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Matrix;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.HeadLineAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.SearchCommtemAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AttentionHead;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.IdentifyActivity;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 关注详情
 */
public class AttentionDetailActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener, CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.OnRefreshListener {

    private final int NAV_LIST_CODE = 0x000001;             // 导航列表
    private final int HEAD_DATA_CODE = 0x000002;            // 头部信息
    private final int GET_DETAIL_LIST_CODE = 0x00000003;   // 获取详情列表
    private final int SUBSCRIBE_OPERATE = 0x00000004;      // 关注/取消关注

    @ViewInject(R.id.activity_attention_detail)
    private DrawerLayout drawerLayout;
    @ViewInject(R.id.photo)
    private ImageView photo;
    @ViewInject(R.id.icon_left)
    private ImageView returnIcon;
    @ViewInject(R.id.end_layout)
    private LinearLayout endLayout;
    @ViewInject(R.id.module_name)
    private TextView name;
    @ViewInject(R.id.icon_more)
    private ImageView iconMore;
    @ViewInject(R.id.attentioned)
    private TextView attentioned;
    @ViewInject(R.id.list_view)
    private ListView listView;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout mRefresh;
    @ViewInject(R.id.can_content_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.no_data_remind)
    private LinearLayout noDataRemindView;
    @ViewInject(R.id.no_competitor_remind)
    private LinearLayout noCompetitorView;
    @ViewInject(R.id.no_competitor_remind_text)
    private TextView noCompetitorText;
    @ViewInject(R.id.no_competitor_remind_btn)
    private TextView noCompetitorBtn;
    @ViewInject(R.id.manager_icon)
    private TextView managerIcon;

    private SearchCommtemAdapter adpter;
    private AttentionHead headdata;
    private List<HeadLineData> list;
    private List<HeadLine> headLines;
    private String infoId;
    private int type;
    private int createType;
    private String prompt;
    private HeadLineAdapter headLineAdapter;
    private boolean isRefresh;
    private String http_type;

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;
    private FileCacheManager cacheManager;
    private String titleCachePath;
    private String navigationCachePath;
    private String detailListCachePaht;

    @Override
    protected int getResourceId() {
        return R.layout.activity_attention_detail;
    }

    @Override
    protected void init() {
        isRefresh = true;
        http_type = "99999";
        initBroadcast();

        type = getIntent().getIntExtra("type", 2);
        infoId = getIntent().getStringExtra("infoId");
        prompt = getIntent().getStringExtra("prompt");
        createType = getIntent().getIntExtra("createType", 1);

        cacheManager = new FileCacheManager();
        titleCachePath = getCacheDir().getPath() + "/attention_title_" + type + "_" + infoId;
        navigationCachePath = getCacheDir().getPath() + "/attention_navigation_" + type + "_" + infoId;
        detailListCachePaht = getCacheDir().getPath() + "/attention_detail_" + type + "_" + infoId;

        String title = getIntent().getStringExtra("title");
        String icon = getIntent().getStringExtra("icon");
        if (icon == null || icon.trim().length() == 0 || type == 3) {
            photo.setVisibility(View.GONE);
        } else {
            photo.setVisibility(View.VISIBLE);
            ImageLoadUtil.loadCircle(mContext, icon + "?imageView2/2/w/80/interlace/1", photo);
        }
        if (photo.getVisibility() == View.GONE)
            name.setMaxEms(15);
        else
            name.setMaxEms(13);
        if (title != null && title.trim().length() > 0) {
            name.setVisibility(View.VISIBLE);
            name.setText(title);
        } else {
            name.setVisibility(View.GONE);
        }

        list = new ArrayList<>();
        adpter = new SearchCommtemAdapter(mContext, list);
        adpter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                adpter.updateTitleColor(position);
                Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
                try {
                    intent.putExtra("id", list.get(position).getId());
                    intent.putExtra("type", list.get(position).getType());
                    intent.putExtra("linkTitle", list.get(position).getTitle());
                    intent.putExtra("linkIcon", list.get(position).getImglist().get(0).getSrc());
                } catch (Exception e) {
                }
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(adpter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        headLineAdapter = new HeadLineAdapter(mContext, new ArrayList<HeadLine>());
        listView.setAdapter(headLineAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                closeRight();
                if (http_type != null && http_type.equals(headLines.get(position).getTypeId()))
                    return;
                if (list != null && list.size() > 0) {
                    list.clear();
                    adpter.updataAdapter(list);
                }
                mRefresh.autoRefresh();
                http_type = headLines.get(position).getTypeId();
                for (HeadLine headLine : headLines)
                    headLine.setCheck(false);
                headLines.get(position).setCheck(true);
                headLineAdapter.updataAdapter(headLines);
            }
        });

        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            private Matrix matrix = new Matrix();
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
//                matrix.setRotate(-720*slideOffset, iconMore.getWidth()/2, iconMore.getHeight()/2);
//                iconMore.setImageMatrix(matrix);
            }
            @Override
            public void onDrawerOpened(View drawerView) {}
            @Override
            public void onDrawerClosed(View drawerView) {}
            @Override
            public void onDrawerStateChanged(int newState) {}
        });

        noCompetitorBtn.setTag(0);
        noCompetitorBtn.setOnClickListener(this);
        managerIcon.setOnClickListener(this);
        iconMore.setOnClickListener(this);
        returnIcon.setOnClickListener(this);
        attentioned.setOnClickListener(this);

        mRefresh.setLoadMoreEnabled(true);
        mRefresh.setRefreshEnabled(true);
        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setOnRefreshListener(this);

        readCache();

        getHeadNav();            //获取导航数据
        getHeadData();           //获取头部数据
        mRefresh.autoRefresh(); //获取详情数据
    }

    private void initBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if (LocalBroadCast.DETAIL_SC_BROAD.equals(action)) {
                    if (list == null || list.size() == 0)
                        return;
                    String id = intent.getStringExtra("id");
                    int isCollection = intent.getIntExtra("isCollection", -1);
                    for (HeadLineData headLineData : list) {
                        if (!headLineData.getId().equals(id))
                            continue;
                        headLineData.setIsFollow(isCollection);
                        break;
                    }
                    adpter.updataAdapter(list);
                }
            }
        });
        localBroadcastManager.registerReceiver(localBroadCast, new IntentFilter(LocalBroadCast.DETAIL_SC_BROAD));
    }

    /* 获取右边导航数据 */
    private void getHeadNav() {
        JsonObject param = new JsonObject();
        param.addProperty("type", type);
        param.addProperty("toId", infoId);
        HttpHelper.getInstance(mContext).subscribeNavList(param, NAV_LIST_CODE, this);
    }

    /* 获取标题栏数据 */
    private void getHeadData() {
        JsonObject param = new JsonObject();
        param.addProperty("id", infoId);
        param.addProperty("type", type);
        HttpHelper.getInstance(mContext).subscribeInfo(param, HEAD_DATA_CODE, this);
    }

    /* 获取列表详情数据 */
    private void getDetailData(int mode, String label) {
        long time = System.currentTimeMillis();
        if (mode == 1) {
            if (list != null && list.size() > 0)
                time = list.get(list.size() - 1).getCreatetime();
            isRefresh = false;
        } else {
            if (list != null && list.size() > 0)
                time = list.get(0).getCreatetime();
            isRefresh = true;
        }
        JsonObject param = new JsonObject();
        param.addProperty("label", label);
        param.addProperty("time", time);
        param.addProperty("mode", mode);
        param.addProperty("type", type);
        param.addProperty("id", infoId);
        HttpHelper.getInstance(mContext).subscribeDetailsList(param, GET_DETAIL_LIST_CODE, this);
    }

    @Override
    public void onStart(int requestType) {
    }

    @Override
    public void onCompleted(int requestType) {
        if (requestType == GET_DETAIL_LIST_CODE) {
            mRefresh.refreshComplete();
            mRefresh.loadMoreComplete();
        }
    }

    @Override
    public void onError(int requestType) {
        if (requestType == SUBSCRIBE_OPERATE) {
            ToasUtil.toast(this, "抱歉，操作失败");
//        } else if(requestType == HEAD_DATA_CODE){
//            setCompetitorRemindView();
        } else if (requestType == SUBSCRIBE_OPERATE) {
            headdata.setIsSubscribe(headdata.getIsSubscribe() == 1 ? 0 : 1);
            if (headdata.getIsSubscribe() == 1)
                attentioned.setText("已关注");
            else
                attentioned.setText("未关注");
        }
        onCompleted(requestType);
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if (data.getErrcode() != 0) {
            onError(requestType);
            return;
        }
        if (requestType == HEAD_DATA_CODE) {
            headdata = data.getEntity(AttentionHead.class);
            setTitleBar();
        } else if (requestType == NAV_LIST_CODE) {
            headLines = data.getList(HeadLine.class);
            if (headLines != null && headLines.size() > 0)
                headLineAdapter.updataAdapter(headLines);
        } else if (requestType == GET_DETAIL_LIST_CODE) {//详情列表
            List<HeadLineData> temp = data.getList(HeadLineData.class);
            if (list == null)
                list = new ArrayList<>();
            // 数据去重
            if (temp != null && temp.size() > 0) {
                List<HeadLineData> removeDatas = new ArrayList<>();
                for (HeadLineData headLineData : temp) {
                    for (HeadLineData showData : list) {
                        if (headLineData.getId() != null && headLineData.getId().equals(showData.getId())) {
                            removeDatas.add(headLineData);
                            break;
                        }
                    }
                }
                for (HeadLineData removeData : removeDatas)
                    temp.remove(removeData);
            }
            if (isRefresh)
                list.addAll(0, temp);
            else
                list.addAll(temp);
            adpter.updataAdapter(list);
            if (list == null || list.size() == 0)
                noDataRemindView.setVisibility(View.VISIBLE);
            else
                noDataRemindView.setVisibility(View.GONE);
        } else if (requestType == SUBSCRIBE_OPERATE) {//关注/取消关注
            headdata.setIsSubscribe((int) Float.parseFloat(data.getData().toString()));
            if (headdata.getIsSubscribe() == 1)
                attentioned.setText("已关注");
            else
                attentioned.setText("未关注");
        }
    }

    private void setTitleBar() {
        if (headdata.getIcon() == null || headdata.getIcon().trim().length() == 0 || type == 3) {
            photo.setVisibility(View.GONE);
        } else {
            photo.setVisibility(View.VISIBLE);
            ImageLoadUtil.loadCircle(mContext, headdata.getIcon()/* + "?imageView2/2/w/80/interlace/1"*/, photo);
        }
        if (photo.getVisibility() == View.GONE)
            name.setMaxEms(15);
        else
            name.setMaxEms(13);
        if (headdata.getTitle() == null || headdata.getTitle().trim().length() == 0) {
            name.setVisibility(View.GONE);
        } else {
            name.setText(headdata.getTitle());
            name.setVisibility(View.VISIBLE);
        }
        if (headdata.getIsCreate() == 1) {
            managerIcon.setVisibility(View.VISIBLE);
            attentioned.setVisibility(View.GONE);
        } else if (createType == 2 || createType == 3) {
            managerIcon.setVisibility(View.GONE);
            attentioned.setVisibility(View.GONE);
        } else {
            managerIcon.setVisibility(View.GONE);
            attentioned.setVisibility(View.VISIBLE);
            if (headdata.getIsSubscribe() == 1)
                attentioned.setText("已关注");
            else
                attentioned.setText("未关注");
        }
        setCompetitorRemindView(headdata);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.icon_more:
                if (drawerLayout.isDrawerOpen(endLayout))
                    closeRight();
                else
                    showRight();
                break;
            case R.id.icon_left:
                this.finish();
                break;
            case R.id.manager_icon:
                String url;
                if (createType == 2 || createType == 3)
                    url = "competeTheme/conditionManage?themeId=" + infoId;
                else
                    url = "competeTheme/buildTheme?themeId=" + infoId;
                JpApplicationWebActivity.gotoWebActivity(this, url);
                break;
            case R.id.attentioned://关注按钮
                JsonObject param = new JsonObject();
                param.addProperty("token", HttpHelper.token);
                param.addProperty("id", infoId);
                param.addProperty("type", type);
                HttpHelper.getInstance(this).subscribeOperate(param, SUBSCRIBE_OPERATE, this);
                headdata.setIsSubscribe(headdata.getIsSubscribe() == 1 ? 0 : 1);
                if (headdata.getIsSubscribe() == 1)
                    attentioned.setText("已关注");
                else
                    attentioned.setText("未关注");
                break;
            case R.id.no_competitor_remind_btn:
                UserData userData = application.getUserData();
                if (userData == null || userData.getIsLogin() != 1) {  // 登陆
                    startActivity(new Intent(this, LoginActivity.class));
                } else if (((int) v.getTag()) == 1) {   // 认证
                    startActivity(new Intent(this, IdentifyActivity.class));
                } else if (((int) v.getTag()) == 2) {    // 管理
                    onClick(managerIcon);
                }
                break;
        }
    }

    /* 打开右边 */
    private void showRight() {
        drawerLayout.openDrawer(endLayout);
    }

    /* 关闭右边 */
    private void closeRight() {
        drawerLayout.closeDrawer(endLayout);
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(endLayout))
            closeRight();
        else
            super.onBackPressed();
    }

    @Override
    public void onRefresh() {
        getDetailData(0, http_type);
    }

    @Override
    public void onLoadMore() {
        getDetailData(1, http_type);
    }

    @Override
    protected void onDestroy() {
        if (headdata.getIsSubscribe() == 0 && attentioned.getVisibility() == View.VISIBLE)
            localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.ATTENTION_EVENT_BROAD)
                    .putExtra("id", infoId).putExtra("isSubscribe", headdata.getIsSubscribe()));
        saveCache(headdata, titleCachePath);
        saveCache(headLines, navigationCachePath);
        saveDetailListCache();
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    /* 从缓存读取数据 */
    private void readCache() {
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                headdata = (AttentionHead) cacheManager.readObject(titleCachePath);
                headLines = (List<HeadLine>) cacheManager.readObject(navigationCachePath);
                list = (List<HeadLineData>) cacheManager.readObject(detailListCachePaht);
                subscriber.onNext(null);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<Void>() {
            @Override
            public void onCompleted() {}
            @Override
            public void onError(Throwable e) {}
            @Override
            public void onNext(Void aVoid) {
                setTitleBar();
                if (headLines != null && headLines.size() > 0)
                    headLineAdapter.updataAdapter(headLines);
                adpter.updataAdapter(list);
            }
        });
    }

    /* 缓存数据 */
    private void saveCache(final Object object, final String cachePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(object, cachePath);
            }
        }).start();
    }

    /* 缓存详情列表数据 */
    private void saveDetailListCache() {
        if (list == null || list.size() == 0)
            return;
        int size = list.size();
        List<HeadLineData> cacheData = new ArrayList<>();
        if (size > 20)
            for (int i = 0; i < 20; i++)
                cacheData.add(list.get(i));
        else
            cacheData.addAll(list);
        saveCache(cacheData, detailListCachePaht);
    }

    private void setCompetitorRemindView(AttentionHead headdata) {
        UserData userData = application.getUserData();
        if (headdata == null || userData == null)
            return;
        if (!"对手".equals(prompt) && !"合作伙伴".equals(prompt) && !"兄弟公司".equals(prompt) && !"公司关注".equals(prompt)) {
            noCompetitorView.setVisibility(View.GONE);
        } else if (headdata.getIsCreate() == 0 && headdata.getCondition() == 0 && userData.getCompanyState() == 0 && userData.getCompanyManage() == 1) {
            noCompetitorView.setVisibility(View.VISIBLE);
            noCompetitorBtn.setVisibility(View.VISIBLE);
            noCompetitorBtn.setText("开始认证");
            noCompetitorBtn.setTag(1);
            if ("对手".equals(prompt))
                noCompetitorText.setText("缺少竞争对手名单，认证组织后可管理");
            else if ("合作伙伴".equals(prompt))
                noCompetitorText.setText("缺少合作伙伴名单，认证组织后可管理");
            else if ("兄弟公司".equals(prompt))
                noCompetitorText.setText("缺少兄弟公司名单，认证组织后可管理");
            else if ("公司关注".equals(prompt))
                noCompetitorText.setText("缺少公司名单，认证组织后可管理");
        } else if (headdata.getIsCreate() == 1 && headdata.getCondition() == 0) {
            noCompetitorView.setVisibility(View.VISIBLE);
            noCompetitorBtn.setVisibility(View.VISIBLE);
            noCompetitorBtn.setText("管理");
            noCompetitorBtn.setTag(2);
            if ("对手".equals(prompt))
                noCompetitorText.setText("缺少竞争对手名单，请进行管理");
            else if ("合作伙伴".equals(prompt))
                noCompetitorText.setText("缺少合作伙伴名单，请进行管理");
            else if ("兄弟公司".equals(prompt))
                noCompetitorText.setText("缺少兄弟公司名单，请进行管理");
            else if ("公司关注".equals(prompt))
                noCompetitorText.setText("缺少公司名单，请进行管理");
        } else if (headdata.getIsCreate() == 0 && headdata.getCondition() == 0 && userData.getCompanyState() == 0 && userData.getCompanyManage() == 0) {
            noCompetitorBtn.setVisibility(View.GONE);
            if ("对手".equals(prompt))
                noCompetitorText.setText("缺少竞争对手名单，暂无数据");
            else if ("合作伙伴".equals(prompt))
                noCompetitorText.setText("缺少合作伙伴名单，暂无数据");
            else if ("兄弟公司".equals(prompt))
                noCompetitorText.setText("缺少兄弟公司名单，暂无数据");
            else if ("公司关注".equals(prompt))
                noCompetitorText.setText("缺少公司名单，暂无数据");
        } else {
            noCompetitorView.setVisibility(View.GONE);
        }
    }
}
